from flask import Blueprint, request, jsonify, render_template, session, redirect, flash, url_for
from sqlalchemy import desc

from applications.models.frontend import Product, ProductCate, User, Comment
from applications.extensions import db
from applications.view.user.decorators import login_required

# 创建商品管理蓝图
product_bp = Blueprint('product', __name__, url_prefix='/product')


# 前台商品列表页面路由
@product_bp.route('/', methods=['GET'])
@product_bp.route('/category/<int:cate_id>', methods=['GET'])
def list(cate_id=None):
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('user.login'))  # 假设登录蓝图名为'user'

    user = User.query.get(user_id)
    categories = ProductCate.query.order_by(desc(ProductCate.id)).all()
    page = int(request.args.get('page', 1))
    per_page = 6
    keyword = request.args.get('keyword', '')

    query = Product.query
    if cate_id:
        query = query.filter(Product.category_id == cate_id)
    if keyword:
        query = query.filter(Product.name.contains(keyword))

    pagination = query.paginate(page=page, per_page=per_page)
    current_category = ProductCate.query.get(cate_id) if cate_id else None

    return render_template(
        'user/product/product.html',
        user=user,
        categories=categories,
        p=pagination,
        current_category=current_category,
        keyword=keyword
    )


# 商品详情页面路由
@product_bp.route('/<int:product_id>', methods=['GET'])
def detail(product_id):
    user_id = session.get('user_id')
    if not user_id:
        return redirect(url_for('user.login'))

    user = User.query.get(user_id)
    product = Product.query.get_or_404(product_id)

    return render_template('user/product/detail.html', user=user, product=product)


# 商品评论路由
@product_bp.route('/<int:product_id>/comment', methods=['POST'])
@login_required
def add_comment(product_id):
    content = request.form.get('content')
    user_id = session.get('user_id')

    if not content:
        return jsonify(success=False, message='评论内容不能为空！')

    comment = Comment(product_id=product_id, user_id=user_id, content=content)
    db.session.add(comment)
    db.session.commit()

    return jsonify(
        success=True,
        comment_id=comment.id,
        username=comment.user.username,
        created_at=comment.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        content=comment.content
    )


# 删除商品评论路由
@product_bp.route('/comment/<int:comment_id>/delete', methods=['POST'])
@login_required
def delete_comment(comment_id):
    user_id = session.get('user_id')
    comment = Comment.query.get(comment_id)

    if comment and comment.user_id == user_id:
        db.session.delete(comment)
        db.session.commit()
        return jsonify(success=True)

    return jsonify(success=False, message='无法删除评论！')


# 注册商品管理蓝图
def register_product_bp(app):
    app.register_blueprint(product_bp)
